{% extends 'base.html' %}

{% block title %}文本编码/解码工具{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800 mb-2">文本编码/解码工具</h1>
        <p class="text-gray-600">提供Base64、URL、HTML实体等多种编码和解码功能</p>
    </div>

    <div class="bg-white shadow-md rounded-lg p-6">
        <div class="mb-6">
            <label for="input-text" class="block text-sm font-medium text-gray-700 mb-2">输入文本</label>
            <textarea id="input-text" rows="6" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">{{ original_text or '' }}</textarea>
            <div class="mt-2 flex justify-between text-sm">
                <span class="text-gray-500">字符数: <span id="char-count">0</span></span>
                <button type="button" id="clear-input" class="text-blue-600 hover:underline">清空</button>
            </div>
        </div>

        <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-2">选择操作</label>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="bg-gray-50 p-4 rounded-md">
                    <h3 class="text-lg font-medium text-gray-800 mb-3">Base64</h3>
                    <div class="space-y-2">
                        <label class="inline-flex items-center">
                            <input type="radio" name="operation" value="base64_encode" {{ 'checked' if operation == 'base64_encode' else '' }} class="form-radio h-4 w-4 text-blue-600 codec-radio">
                            <span class="ml-2 text-gray-700">Base64 编码</span>
                        </label>
                        <br>
                        <label class="inline-flex items-center">
                            <input type="radio" name="operation" value="base64_decode" {{ 'checked' if operation == 'base64_decode' else '' }} class="form-radio h-4 w-4 text-blue-600 codec-radio">
                            <span class="ml-2 text-gray-700">Base64 解码</span>
                        </label>
                    </div>
                </div>

                <div class="bg-gray-50 p-4 rounded-md">
                    <h3 class="text-lg font-medium text-gray-800 mb-3">URL</h3>
                    <div class="space-y-2">
                        <label class="inline-flex items-center">
                            <input type="radio" name="operation" value="url_encode" {{ 'checked' if operation == 'url_encode' else '' }} class="form-radio h-4 w-4 text-blue-600 codec-radio">
                            <span class="ml-2 text-gray-700">URL 编码</span>
                        </label>
                        <br>
                        <label class="inline-flex items-center">
                            <input type="radio" name="operation" value="url_decode" {{ 'checked' if operation == 'url_decode' else '' }} class="form-radio h-4 w-4 text-blue-600 codec-radio">
                            <span class="ml-2 text-gray-700">URL 解码</span>
                        </label>
                    </div>
                </div>

                <div class="bg-gray-50 p-4 rounded-md">
                    <h3 class="text-lg font-medium text-gray-800 mb-3">HTML</h3>
                    <div class="space-y-2">
                        <label class="inline-flex items-center">
                            <input type="radio" name="operation" value="html_encode" {{ 'checked' if operation == 'html_encode' else '' }} class="form-radio h-4 w-4 text-blue-600 codec-radio">
                            <span class="ml-2 text-gray-700">HTML 实体编码</span>
                        </label>
                        <br>
                        <label class="inline-flex items-center">
                            <input type="radio" name="operation" value="html_decode" {{ 'checked' if operation == 'html_decode' else '' }} class="form-radio h-4 w-4 text-blue-600 codec-radio">
                            <span class="ml-2 text-gray-700">HTML 实体解码</span>
                        </label>
                    </div>
                </div>
            </div>
        </div>

        <div class="mb-6">
            <button id="execute-btn" type="button" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                <i class="fas fa-play mr-2"></i>执行
            </button>
        </div>

        <div id="result-container" class="mt-8 hidden">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">结果</h2>
            <div class="relative">
                <textarea id="result" readonly rows="6" class="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-50"></textarea>
                <button id="copy-btn" class="absolute top-2 right-2 px-2 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500">
                    <i class="fas fa-copy"></i>
                </button>
            </div>
            <div class="mt-4 text-right">
                <button id="download-btn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500">
                    <i class="fas fa-download mr-1"></i>下载结果
                </button>
            </div>
        </div>

        <!-- 加载指示器 -->
        <div id="loading-indicator" class="hidden mt-6">
            <div class="flex justify-center items-center mb-4">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            </div>
            <p class="text-center text-gray-600 text-sm">正在处理中...</p>
        </div>
    </div>

    <div class="mt-8 bg-blue-50 rounded-lg p-4">
        <h3 class="text-lg font-medium text-blue-800 mb-2">使用提示</h3>
        <ul class="list-disc pl-5 text-blue-700 space-y-1">
            <li>Base64 编码可用于将二进制数据转换为文本格式，例如在 HTML 中嵌入图片</li>
            <li>URL 编码可确保 URL 中的特殊字符正确传输，特别是包含非 ASCII 字符时</li>
            <li>HTML 实体编码可防止跨站脚本攻击(XSS)，将 HTML 标签等特殊字符转换为安全形式</li>
        </ul>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const inputText = document.getElementById('input-text');
    const charCount = document.getElementById('char-count');
    const clearBtn = document.getElementById('clear-input');
    const executeBtn = document.getElementById('execute-btn');
    const resultContainer = document.getElementById('result-container');
    const resultArea = document.getElementById('result');
    const copyBtn = document.getElementById('copy-btn');
    const downloadBtn = document.getElementById('download-btn');
    const loadingIndicator = document.getElementById('loading-indicator');
    const radioButtons = document.querySelectorAll('.codec-radio');
    
    // 初始化字符计数
    function updateCharCount() {
        charCount.textContent = inputText.value.length;
    }
    
    // 监听输入变化更新字符计数
    inputText.addEventListener('input', updateCharCount);
    updateCharCount();
    
    // 清空按钮
    clearBtn.addEventListener('click', function() {
        inputText.value = '';
        updateCharCount();
        resultContainer.classList.add('hidden');
    });
    
    // 执行按钮
    executeBtn.addEventListener('click', function() {
        const text = inputText.value;
        if (!text.trim()) {
            showMessage('请输入要处理的文本', 'error');
            return;
        }
        
        // 获取选中的操作类型
        const selectedRadio = document.querySelector('input[name="operation"]:checked');
        if (!selectedRadio) {
            showMessage('请选择一个操作类型', 'error');
            return;
        }
        
        const operation = selectedRadio.value;
        
        // 显示加载指示器
        loadingIndicator.classList.remove('hidden');
        
        // 准备发送的数据
        const formData = new FormData();
        formData.append('text', text);
        formData.append('operation', operation);
        
        // 发送AJAX请求
        fetch('{{ url_for("text_tools.text_codec_ajax") }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            return response.json();
        })
        .then(data => {
            // 隐藏加载指示器
            loadingIndicator.classList.add('hidden');
            
            if (data.error === 0) {
                // 显示结果
                resultArea.value = data.result;
                resultContainer.classList.remove('hidden');
                showMessage('处理成功');
            } else {
                showMessage(data.message || '处理失败', 'error');
            }
        })
        .catch(error => {
            // 隐藏加载指示器
            loadingIndicator.classList.add('hidden');
            showMessage('请求出错: ' + error.message, 'error');
        });
    });
    
    // 复制按钮
    copyBtn.addEventListener('click', function() {
        const textToCopy = resultArea.value;
        navigator.clipboard.writeText(textToCopy).then(function() {
            showMessage('文本已复制到剪贴板');
        }, function() {
            showMessage('复制失败，请手动复制', 'error');
        });
    });
    
    // 下载按钮
    downloadBtn.addEventListener('click', function() {
        const textToDownload = resultArea.value;
        const blob = new Blob([textToDownload], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = '编码结果.txt';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        showMessage('文件已下载');
    });
    
    // 显示消息提示
    function showMessage(message, type = 'success') {
        const toast = document.createElement('div');
        
        toast.className = 'fixed bottom-4 right-4 px-4 py-2 rounded shadow-lg z-50 transition-opacity duration-500';
        toast.style.opacity = '0';
        
        if (type === 'error') {
            toast.classList.add('bg-red-500', 'text-white');
        } else {
            toast.classList.add('bg-green-500', 'text-white');
        }
        
        toast.textContent = message;
        
        document.body.appendChild(toast);
        
        // 淡入效果
        setTimeout(() => {
            toast.style.opacity = '1';
        }, 10);
        
        // 3秒后淡出并移除
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 500);
        }, 3000);
    }

    // 设置默认选中第一个单选按钮
    if (!document.querySelector('input[name="operation"]:checked')) {
        radioButtons[0].checked = true;
    }
});
</script>
{% endblock %}